<template>
	<view class="template-avatar tn-safe-area-inset-bottom">
		<!-- 顶部自定义导航 -->
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="cropper-options">
				<view class="cropper-options__item" @tap="chooseImage">选择图片</view>
				<view class="cropper-options__item" @tap="switchBorderRect">{{ switchText }}</view>
			</view>
		</view>

		<tn-cropper :imageUrl="imageUrl" :isRound="isRound" @cropper="cropperFinish"></tn-cropper>
	</view>
</template>

<script>
	import { upload, uploadFullUrl } from '@/api/common/file';
	import { saveUser } from '@/api/sys/userInfo';
	export default {
		name: 'TemplateAvatar',
		components: {},
		data() {
			return {
				imageUrl: '',
				isRound: true,
				switchText: '正方形裁剪',
				showCropperImage: false,
				cropperImageUrl: ''
			}
		},
		methods: {
			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths[0]
						this.imageUrl = tempFilePaths
					}
				})
			},
			// 切换裁剪框形状
			switchBorderRect() {
				this.isRound = !this.isRound
				if (this.isRound) {
					this.switchText = '正方形裁剪'
				} else {
					this.switchText = '圆形裁剪'
				}
			},
			// 裁剪完成
			cropperFinish(res) {
				let fileName = this.$tn.uuid() + ".png";
				let filePath;
				let file = null;
				if (res.url) {
					filePath = res.url
				}
				if (res.base64) {
					file = this.$common.base64ToFile(res.base64);
				}
				uni.uploadFile({
					url: uploadFullUrl,
					filePath: filePath,
					name: 'file',
					formData: {
						fileName: fileName,
						superPath: 'upload/resoures/img/avater'
					},
					success: (uploadFileRes) => {
						//头像上传成功之后，更新用户的avatar字段
						let data = JSON.parse(uploadFileRes.data);
						console.info(data.result.path)
						let entity = {
							id: this.vuex_user.id,
							avatar: data.result.path
						}
						saveUser(entity).then(res => {
							this.$store.commit('$tStore', {
								name: 'vuex_user.avatar',
								value: data.result.path
							});
						}).finally(res => {
							this.$common.navigateBack();
						});
					}
				});

			}
		}
	}
</script>

<style lang="scss" scoped>
	.cropper-options {
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;

		&__item {
			color: #FFFFFF;
			font-size: 28rpx;
			padding: 18rpx 56rpx;
			width: 300rpx;
			text-align: center;
			border: 2rpx solid #FFFFFF;
			z-index: 1000;

			&:nth-child(1) {
				border-right: none;
			}
		}
	}
</style>